<template>
	<div class="app-container" v-loading="data.mtloading">
		<el-form :model="data.info" :rules="data.rules" class="w-full" :label-width="language == 'en' ? '155' : '120px'"
			ref="ruleFormRef">

			<el-form-item :label="$t('goods.corner.activitName') + ':'" prop="pick_name" class="w-1/2">
				<el-input v-model="data.info.pick_name" :placeholder="$t('message.pleaseEnter')" />
			</el-form-item>

			<el-form-item :label="$t('marketing.reduction.type') + ':'" prop="pick_type" class="w-1/2">
				<el-select v-model="data.info.pick_type" :placeholder="$t('message.pleaseSelect')" disabled>
					<el-option :label="$t('marketing.pickupcode.systemRandom')" :value="1" />
					<el-option :label="$t('marketing.pickupcode.choice')" :value="2" />
				</el-select>
			</el-form-item>

			<el-form-item :label="$t('marketing.pickupcode.bgImage') + ':'" prop="bg_pic" class="w-1/2">
				<el-input v-model="data.info.bg_pic" readonly :placeholder="$t('goods.corner.pleaseUpload')">
					<template #append>
						<Upload :list="{ 'data': 'pickup_code', 'list': false }" :type="1" :uptype="2"
							@exposeData="expose" />
					</template>
					<template #suffix>
						<el-icon class="ml-2" size="20" @click="urlimg(data.info.bg_pic)">
							<Picture />
						</el-icon>
					</template>
				</el-input>
			</el-form-item>

			<el-form-item :label="$t('goods.corner.timeType') + ':'" prop="timetype" class="w-1/2">
				<el-select v-model="data.timetype" :placeholder="$t('message.pleaseSelect')">
					<el-option :label="$t('goods.corner.timeLimit')" :value="1" />
					<el-option :label="$t('goods.corner.indefinite')" :value="2" />
				</el-select>
			</el-form-item>

			<el-form-item v-if="data.timetype == 1" :label="$t('date.activityTime') + ':'" prop="time" class="w-1/2">
				<el-date-picker v-model="data.info.time" :disabled-date="disabledDate" type="datetimerange"
					:range-separator="$t('public.to')" :start-placeholder="$t('date.startTimes')"
					:end-placeholder="$t('date.endTimes')" format="YYYY-MM-DD HH:mm:ss" value-format="x"
					:shortcuts="shortcuts" time-format="A hh:mm:ss" />
			</el-form-item>

			<el-form-item v-if="data.timetype == 2" :label="$t('date.activityTime') + ':'" prop="ditem" class="w-1/2">
				<el-date-picker v-model="data.info.ditem" :disabled-date="disabledDate" type="datetime"
					format="YYYY-MM-DD HH:mm:ss" value-format="x" style="width: 100%;"
					:placeholder="$t('message.pleaseSelect')" time-format="HH:mm:ss" />
			</el-form-item>

			<el-form-item :label="$t('machine.marketing.Applicable') + ':'" prop="grouping" class="w-1/2"
				v-prmis="'machine_group_mg_getList'">

				<el-cascader :placeholder="$t('message.selectGroup')" style="width:40%;margin-right: 1%;" clearable
					:props="propss" v-model="data.groupValue" @change="getmping($event, 1)"
					@visible-change="onVisibleChange" />

				<el-select v-model="data.macping" :placeholder="$t('message.pleaseMachine')" clearable filterable
					style="width:40%;" @change="getmping($event, 2)">
					<el-option v-for="item in data.maclist" :key="item.m_id"
						:label="item.machine_id + '-' + item.machine_name" :value="item.machine_id" />
				</el-select>

				<div class="w-full dashed mt-2 p-2" v-if="data.grouping.length != 0">
					<el-tag v-for="item, key of data.grouping" :key="key" closable :disable-transitions="false"
						class="mr-2" :type="item.mg_id == undefined ? '' : 'warning'" size="large"
						@close="handleClose(key)">
						{{ item.machine_id || '' }}{{ item.mg_name || item.label || ' - ' + item.machine_name }}
					</el-tag>
				</div>

			</el-form-item>

			<el-form-item :label="$t('goods.corner.applica') + ':'" prop="goodsList" class="w-1/2">
				<el-select v-model="data.info.goodsList" :placeholder="$t('message.pleaseSelect')" clearable filterable
					multiple @change="godoption">
					<template #header>
						<el-checkbox v-model="data.godcheckAll" :indeterminate="data.godindeterminate"
							@change="godsCheckAll">{{ $t('public.selectAll') }}</el-checkbox>
					</template>
					<el-option v-for="item in data.godlist" :key="item.m_id" :label="item.g_id + ' - ' + item.g_name"
						:value="item.g_id" />
				</el-select>
			</el-form-item>

			<el-form-item :label="$t('marketing.reduction.desc') + ':'" prop="desc" class="w-1/2">
				<el-input v-model="data.info.desc" type="textarea" :autosize="{ minRows: 8, maxRows: 10 }"
					:placeholder="$t('message.pleaseEnter')" />
			</el-form-item>

			<div class="w-1/2 text-center mt-4 ml-6">
				<div class="inline-block">
					<el-button type="primary" @click="submit(ruleFormRef)">{{ $t('public.save') }}</el-button>
					<el-button @click="getinfo">{{ $t('public.cancel') }}</el-button>
				</div>
			</div>

		</el-form>

		<!-- 图片展示 -->
		<el-dialog v-model="data.demonstrate" center width="30%">
			<div class="flex justify-center">
				<el-image class="max-w-80" :src="data.info.bg_pic" fit="fill" />
			</div>
		</el-dialog>

	</div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import Upload from '@/components/Upload/index.vue';
import { updateActivityPick } from '@/api/marketing';
import { getmachineList } from '@/api/machine';
import { getgroupList, getListgroupmg } from "@/api/machine_type";
import { getgoodsList } from '@/api/goods';
import { useRouter, useRoute } from "vue-router";
import { onMounted } from 'vue'
let language = ref()
const { locale } = useI18n()
onMounted(() => {
	language.value = locale.value
})
let ruleFormRef = ref<any>();
const router = useRouter()
const route = useRoute()

let shortcuts = [
	{
		text: '最近七天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
			return [end, start];
		}
	},
	{
		text: '最近三十天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
			return [end, start];
		}
	},
	{
		text: '最近三个月',
		value: () => {
			const start = new Date();
			const end = new Date();
			start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
			return [end, start];
		}
	}
];

let data = reactive({
	groupValue: [],
	nodesData: [],
	demonstrate: false, // 弹窗
	mtloading: false, // 加载
	godcheckAll: false, // 商品全选
	godindeterminate: false, // 商品部分选中
	timetype: 1, // 1日期范围、2无限期
	maclist: [], // 设备列表
	godlist: [], // 商品列表

	macgrouping: [], // 设备分组
	bindmacping: [], // 设备分组绑定的设备
	grouping: [], // 展示分组/设备
	macping: '', // 选中的分组/设备

	info: {}, // 主体数据
	rules: { // 表单验证
		pick_name: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		// bg_pic:{ required: true, message:  $t('message.pleaseUpload'), trigger: 'blur' },
		ditem: { required: true, message: $t('message.pleaseSelect'), trigger: 'blur' },
		time: { required: true, message: $t('message.pleaseSelect'), trigger: 'change' },
		machineList: { required: true, message: $t('message.pleaseSelect'), trigger: 'change' },
		goodsList: { required: true, message: $t('message.pleaseSelect'), trigger: 'change' },
	},
})
const propss = reactive(
	{
		checkStrictly: true,
		lazy: true,
		multiple: false,
		async lazyLoad(node: any, resolve: any) {
			const { level, value } = node
			let nodes = await getgroupList({ pid: value });
			if (nodes.state == 100 || nodes.state == 300) {
				resolve([]);
			}
			const nodesa = nodes.data.map((item) => ({
				value: item.mg_id,
				label: item.mg_id + '-' + item.mg_name
			}))
			nodes.data.forEach(item => {
				data.nodesData.push({
					value: item.mg_id,
					label: item.mg_id + '-' + item.mg_name
				})
			})
			resolve(nodesa);
		}
	}
)
// 获取主体信息
let getinfo = () => {
	let info = JSON.parse(decodeURI(route.query.l)).info
	data.grouping = []
	data.info = {
		id: info.id,
		pick_name: info.pick_name,
		desc: info.desc,
		bg_pic: info.bg_pic,
		time: [],
		ditem: '',
		pick_type: info.pick_type,
		machineList: [],
		goodsList: []
	}

	if (info.end_time == '' || info.end_time == null) {
		data.timetype = 2
		data.info.ditem = Number(info.start_time + '000')
	} else {
		data.timetype = 1
		data.info.time = [Number(info.start_time + '000'), Number(info.end_time + '000')]
	}

	for (let item of info.machineList) {
		data.grouping.push(item)
	}

	for (let item of info.goodsList) {
		data.info.goodsList.push(item.g_id)
	}

}

// 获取接口信息
let geturlinfo = async () => {
	// 获取设备信息
	await getmachineList().then(res => {
		if (res.state == 200) {
			data.maclist = res.data
		}
	})
	// 获取商品信息
	await getgoodsList().then(res => {
		if (res.state == 200) {
			data.godlist = res.data
		}
	})

	// 获取设备分组
	await getgroupList().then(res => {
		if (res.state == 200) {
			data.macgrouping = res.data
		}
	})

	// 获取分组中的设备
	await getListgroupmg().then(res => {
		if (res.state == 200) {
			data.bindmacping = res.data
		}
	})

}

// 上传返回
let expose = (e) => {
	if (e.status == 200) {
		data.info.bg_pic = e.file.response.data
	} else {
		data.info.bg_pic = ''
	}
}

// 查看图片
let urlimg = (e) => {
	if (e == '') {
		return;
	}
	data.demonstrate = true;
}

// 日期选择
let disabledDate = (time: Date) => {
	return time.getTime() < Date.now() - 3600 * 1000 * 24 * 1
}

// 选中商品
let godoption = () => {
	if (data.info.goodsList.length == 0) {
		data.godcheckAll = false;
		data.godindeterminate = false;
	} else {
		if (data.info.goodsList.length == data.godlist.length) {
			data.godcheckAll = true;
			data.godindeterminate = false;
		} else {
			data.godcheckAll = false;
			data.godindeterminate = true;
		}
	}
}

// 商品全选
let godsCheckAll = (val) => {
	if (val) {
		data.info.goodsList = data.godlist.map(_ => _.g_id);
		data.godcheckAll = true
		data.godindeterminate = false
	} else {
		data.info.goodsList = [];
	}
}
let onVisibleChange = () => {
	data.groupValue = []
}
// 选中分组/设备
let getmping = (e, k) => {
	let obj = ''
	let status = true
	if (k == 1) {
		// 分组
		data.nodesData.map((item) => {
			if (item.value === e[e.length - 1]) obj = item
		})
		for (let item of data.grouping) {
			if (item.value == obj.value) {
				status = false
			}
		}
	} else {
		// 设备
		data.maclist.map((item) => { if (item.machine_id === e) obj = item })
		for (let item of data.grouping) {
			if (item.m_id == obj.m_id) {
				status = false
			}
		}
		data.macping = ''
	}
	if (status) {
		data.grouping.push(obj)
	}

}

// 删除选中的设备分组/设备
let handleClose = (e) => {
	data.grouping.splice(e, 1)
}

// 保存
let submit = (formEl: FormInstance | undefined) => {

	if (!formEl) return;
	formEl.validate((valid, fields) => {
		if (valid) {
			let obj = {}
			let machine = []
			for (let key in data.info) {
				if (key != 'time' && key != 'ditem') {
					obj[key] = data.info[key]
				}
			}

			obj.start_time = Math.floor(data.info.ditem / 1000)
			obj.end_time = ''
			if (data.timetype == 1) {
				obj.start_time = Math.floor(data.info.time[0] / 1000)
				obj.end_time = Math.floor(data.info.time[1] / 1000)
			}

			if (data.grouping.length == 0) {
				ElMessage({
					message: $t('message.pleaseSelectMachine'),
					type: 'error'
				})
				return
			}

			if (data.grouping.length != 0) {
				let grouping = []
				for (let item of data.grouping) {
					// 设备
					if (item.mg_id != undefined) {
						data.bindmacping.map((ime) => {
							if (item.mg_id === ime.mg_id) {
								grouping.push(ime.machine_id)
							}
						})
					}

					if (item.machine_id != undefined) {
						grouping.push(item.machine_id)
					}
					// 设备分组
					if (item.value != undefined) {
						data.bindmacping.map((ime) => {
							if (item.value === ime.mg_id) {
								grouping.push(ime.machine_id)
							}
						})
					}
				}
				// 设备分组放入指定设备中
				machine = [...machine, ...grouping]
			}

			// 去除重复的设备编号
			obj.machineList = [...new Set(machine)]

			data.mtloading = true
			updateActivityPick(obj).then(res => {
				data.mtloading = false
				if (res.state == 200) {
					ElMessage({
						message: $t('message.completedAdd'),
						type: 'success'
					})
					router.back()
					return
				}
				ElMessage({
					message: $t('message.networkFailed'),
					type: 'error'
				})
			})
		}
	})
}

getinfo()
geturlinfo()

</script>
<style type="text/css">
.dashed {
	border: 2px dashed var(--el-border-color);
}
</style>